<template>
  <div class="security-compliance-container">
    <el-card class="compliance-card">
      <template #header>
        <div class="card-header">
          <h2>安全合规性检查</h2>
          <div class="header-actions">
            <el-button type="primary" @click="openNewCheckDialog" icon="el-icon-plus">
              新建检查
            </el-button>
            <el-dropdown @command="handleHeaderCommand">
              <el-button icon="el-icon-more">
                更多 <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="batchDelete">批量删除</el-dropdown-item>
                  <el-dropdown-item command="exportResults">导出结果</el-dropdown-item>
                  <el-dropdown-item command="refresh">刷新</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>

      <!-- 搜索筛选区域 -->
      <div class="search-filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索检查名称、目标"
              prefix-icon="el-icon-search"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-col>
          <el-col :span="5">
            <el-select
              v-model="searchForm.standard"
              placeholder="选择标准"
              clearable
              filterable
            >
              <el-option
                v-for="item in complianceStandards"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select
              v-model="searchForm.status"
              placeholder="选择状态"
              clearable
            >
              <el-option label="待执行" value="pending" />
              <el-option label="执行中" value="running" />
              <el-option label="已完成" value="completed" />
              <el-option label="执行失败" value="failed" />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              clearable
            />
          </el-col>
        </el-row>
        <div class="filter-actions">
          <el-button type="default" @click="resetSearch" icon="el-icon-refresh">
            重置
          </el-button>
          <el-button type="primary" @click="handleSearch" icon="el-icon-search">
            搜索
          </el-button>
          <el-button @click="toggleAdvancedFilter">
            {{ showAdvancedFilter ? '收起高级筛选' : '高级筛选' }}
          </el-button>
        </div>
        
        <!-- 高级筛选 -->
        <div v-if="showAdvancedFilter" class="advanced-filters">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-select
                v-model="searchForm.severity"
                placeholder="合规风险级别"
                clearable
              >
                <el-option label="高风险" value="high" />
                <el-option label="中风险" value="medium" />
                <el-option label="低风险" value="low" />
                <el-option label="合规" value="compliant" />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select
                v-model="searchForm.checkType"
                placeholder="检查类型"
                clearable
              >
                <el-option label="自动检查" value="auto" />
                <el-option label="手动检查" value="manual" />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select
                v-model="searchForm.targetType"
                placeholder="目标类型"
                clearable
              >
                <el-option label="网站" value="website" />
                <el-option label="API" value="api" />
                <el-option label="资产组" value="asset_group" />
                <el-option label="内部系统" value="internal" />
              </el-select>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 合规检查统计概览 -->
      <div class="compliance-overview">
        <el-row :gutter="20">
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="4">
            <el-card class="stat-card">
              <div class="overview-content">
                <div class="stat-value high-risk">
                  <el-statistic :value="totalHighRisk" :precision="0">
                    <template #suffix>项</template>
                  </el-statistic>
                </div>
                <div class="overview-desc">高风险不合规</div>
                <div class="trend-indicator trend-up">
                  <i class="el-icon-caret-top"></i> 12% 较上月
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="4">
            <el-card class="stat-card">
              <div class="overview-content">
                <div class="stat-value medium-risk">
                  <el-statistic :value="totalMediumRisk" :precision="0">
                    <template #suffix>项</template>
                  </el-statistic>
                </div>
                <div class="overview-desc">中风险不合规</div>
                <div class="trend-indicator trend-down">
                  <i class="el-icon-caret-bottom"></i> 8% 较上月
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="4">
            <el-card class="stat-card">
              <div class="overview-content">
                <div class="stat-value low-risk">
                  <el-statistic :value="totalLowRisk" :precision="0">
                    <template #suffix>项</template>
                  </el-statistic>
                </div>
                <div class="overview-desc">低风险不合规</div>
                <div class="trend-indicator trend-neutral">
                  <i class="el-icon-minus"></i> 0% 较上月
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="4">
            <el-card class="stat-card">
              <div class="overview-content">
                <div class="stat-value compliant">
                  <el-statistic :value="totalCompliant" :precision="0">
                    <template #suffix>项</template>
                  </el-statistic>
                </div>
                <div class="overview-desc">合规项</div>
                <div class="trend-indicator trend-up">
                  <i class="el-icon-caret-top"></i> 15% 较上月
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="4">
            <el-card class="stat-card">
              <div class="overview-content">
                <div class="stat-value compliance-rate">
                  <el-statistic :value="complianceRate" :precision="1">
                    <template #suffix>%</template>
                  </el-statistic>
                </div>
                <div class="overview-desc">合规率</div>
                <div class="trend-indicator trend-up">
                  <i class="el-icon-caret-top"></i> 5.2% 较上月
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="4">
            <el-card class="stat-card">
              <div class="overview-content">
                <div class="stat-value total-checks">
                  <el-statistic :value="totalChecks" :precision="0">
                    <template #suffix>次</template>
                  </el-statistic>
                </div>
                <div class="overview-desc">已执行检查</div>
                <div class="trend-indicator trend-up">
                  <i class="el-icon-caret-top"></i> 23% 较上月
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 合规检查列表表格 -->
      <div class="compliance-table-section">
        <el-table
          v-loading="loading"
          :data="complianceChecks"
          @selection-change="handleSelectionChange"
          border
          fit
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="检查名称" min-width="180">
            <template #default="scope">
              <div class="check-name">
                <el-tooltip :content="scope.row.description" placement="top">
                  <div class="name-content">{{ scope.row.name }}</div>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="standard" label="合规标准" min-width="120">
            <template #default="scope">
              <el-tag :type="getStandardTagType(scope.row.standard)">
                {{ getStandardLabel(scope.row.standard) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="target" label="检查目标" min-width="150">
            <template #default="scope">
              <div class="target-value">{{ scope.row.target }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ getStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="overallRisk" label="整体风险" width="100">
            <template #default="scope">
              <el-tag :type="getRiskLevelTagType(scope.row.overallRisk)">
                {{ getRiskLevelLabel(scope.row.overallRisk) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="checkCount" label="检查项数" width="100">
            <template #default="scope">
              <div>
                <span>{{ scope.row.checkCount }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="failedCount" label="不合规项" width="100">
            <template #default="scope">
              <div :class="scope.row.failedCount > 0 ? 'failed-count' : ''">
                <span>{{ scope.row.failedCount }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="160" sortable />
          <el-table-column prop="endTime" label="结束时间" width="160" sortable />
          <el-table-column prop="createdBy" label="创建人" width="100" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button
                type="text"
                size="small"
                @click="viewComplianceDetails(scope.row.id)"
                :disabled="scope.row.status !== 'completed'"
              >
                查看结果
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="runComplianceCheck(scope.row.id)"
                :disabled="scope.row.status === 'running'"
              >
                重新执行
              </el-button>
              <el-dropdown @command="(command) => handleActionCommand(command, scope.row.id)">
                <el-button type="text" size="small">
                  更多 <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit">编辑</el-dropdown-item>
                    <el-dropdown-item command="export">导出报告</el-dropdown-item>
                    <el-dropdown-item command="share">分享结果</el-dropdown-item>
                    <el-dropdown-item command="clone">克隆</el-dropdown-item>
                    <el-dropdown-item command="delete" divided>
                      <span style="color: #F56C6C">删除</span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <div class="pagination-container">
          <div class="pagination-info">
            共 {{ total }} 条数据，当前显示第 {{ (currentPage - 1) * pageSize + 1 }}-{{
              Math.min(currentPage * pageSize, total)
            }} 条
          </div>
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[10, 20, 50, 100]"
          />
        </div>
      </div>

      <!-- 批量操作栏 -->
      <div v-if="selectedChecks.length > 0" class="batch-actions">
        <span>已选择 {{ selectedChecks.length }} 项</span>
        <el-button type="danger" @click="confirmBatchDelete">
          <i class="el-icon-delete"></i> 批量删除
        </el-button>
        <el-button @click="batchRunChecks">
          <i class="el-icon-refresh"></i> 批量执行
        </el-button>
        <el-button @click="batchExportReports">
          <i class="el-icon-download"></i> 批量导出
        </el-button>
        <el-button @click="clearSelection">
          <i class="el-icon-circle-close"></i> 取消选择
        </el-button>
      </div>
    </el-card>

    <!-- 新建合规检查对话框 -->
    <el-dialog
      v-model="newCheckDialogVisible"
      title="新建合规检查"
      width="60%"
      :before-close="handleDialogClose"
    >
      <el-form
        :model="newCheckForm"
        :rules="checkFormRules"
        ref="checkFormRef"
        label-width="100px"
      >
        <el-form-item label="检查名称" prop="name">
          <el-input
            v-model="newCheckForm.name"
            placeholder="请输入检查名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="newCheckForm.description"
            placeholder="请输入检查描述"
            type="textarea"
            rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="合规标准" prop="standard">
          <el-select
            v-model="newCheckForm.standard"
            placeholder="请选择合规标准"
            filterable
            multiple
          >
            <el-option
              v-for="item in complianceStandards"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="检查目标" prop="target">
          <el-input
            v-model="newCheckForm.target"
            placeholder="请输入检查目标（URL/IP/资产组ID）"
            maxlength="200"
          />
        </el-form-item>
        
        <el-form-item label="目标类型" prop="targetType">
          <el-radio-group v-model="newCheckForm.targetType">
            <el-radio label="website">网站</el-radio>
            <el-radio label="api">API</el-radio>
            <el-radio label="asset_group">资产组</el-radio>
            <el-radio label="internal">内部系统</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="检查类型" prop="checkType">
          <el-radio-group v-model="newCheckForm.checkType">
            <el-radio label="auto">自动检查</el-radio>
            <el-radio label="manual">手动检查</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="检查范围" prop="checkScope">
          <el-checkbox-group v-model="newCheckForm.checkScope">
            <el-checkbox label="authentication">身份认证</el-checkbox>
            <el-checkbox label="authorization">授权访问</el-checkbox>
            <el-checkbox label="data_protection">数据保护</el-checkbox>
            <el-checkbox label="encryption">加密机制</el-checkbox>
            <el-checkbox label="input_validation">输入验证</el-checkbox>
            <el-checkbox label="output_encoding">输出编码</el-checkbox>
            <el-checkbox label="session_management">会话管理</el-checkbox>
            <el-checkbox label="error_handling">错误处理</el-checkbox>
            <el-checkbox label="logging">日志记录</el-checkbox>
            <el-checkbox label="configuration">配置管理</el-checkbox>
            <el-checkbox label="dependency_security">依赖安全</el-checkbox>
            <el-checkbox label="network_security">网络安全</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="执行方式" prop="executionMode">
          <el-radio-group v-model="newCheckForm.executionMode">
            <el-radio label="immediate">立即执行</el-radio>
            <el-radio label="scheduled">定时执行</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item
          v-if="newCheckForm.executionMode === 'scheduled'"
          label="执行时间"
          prop="scheduleTime"
        >
          <el-date-picker
            v-model="newCheckForm.scheduleTime"
            type="datetime"
            placeholder="选择执行时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item label="通知设置" prop="notificationEnabled">
          <el-switch v-model="newCheckForm.notificationEnabled" />
        </el-form-item>
        
        <el-form-item
          v-if="newCheckForm.notificationEnabled"
          label="通知条件"
          prop="notificationCondition"
        >
          <el-select
            v-model="newCheckForm.notificationCondition"
            placeholder="选择通知条件"
          >
            <el-option label="全部结果" value="all" />
            <el-option label="仅高风险" value="high_only" />
            <el-option label="高风险和中风险" value="high_medium" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="submitCheckForm">确认创建</el-button>
      </template>
    </el-dialog>

    <!-- 合规检查详情对话框 -->
    <el-dialog
      v-model="checkDetailsDialogVisible"
      :title="`合规检查详情 - ${currentCheck?.name || ''}`"
      width="80%"
      :before-close="handleDialogClose"
      :close-on-click-modal="false"
    >
      <div v-if="currentCheck" class="check-details-container">
        <!-- 基本信息 -->
        <div class="details-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="检查名称">{{ currentCheck.name }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusTagType(currentCheck.status)">
                {{ getStatusLabel(currentCheck.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="合规标准">
              <div class="standards-list">
                <el-tag
                  v-for="standard in currentCheck.standard"
                  :key="standard"
                  :type="getStandardTagType(standard)"
                  size="small"
                  class="standard-tag"
                >
                  {{ getStandardLabel(standard) }}
                </el-tag>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="整体风险">
              <el-tag :type="getRiskLevelTagType(currentCheck.overallRisk)">
                {{ getRiskLevelLabel(currentCheck.overallRisk) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="检查目标">{{ currentCheck.target }}</el-descriptions-item>
            <el-descriptions-item label="目标类型">{{ getTargetTypeLabel(currentCheck.targetType) }}</el-descriptions-item>
            <el-descriptions-item label="检查项数">{{ currentCheck.checkCount }}</el-descriptions-item>
            <el-descriptions-item label="不合规项">{{ currentCheck.failedCount }}</el-descriptions-item>
            <el-descriptions-item label="合规项">{{ currentCheck.passedCount }}</el-descriptions-item>
            <el-descriptions-item label="合规率">{{ currentCheck.complianceRate }}%</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ currentCheck.startTime }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ currentCheck.endTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="创建人">{{ currentCheck.createdBy }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentCheck.createdAt }}</el-descriptions-item>
            <el-descriptions-item label="描述" :span="2">{{ currentCheck.description || '-' }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <!-- 合规检查结果概览图表 -->
        <div class="details-section">
          <h3>合规检查结果概览</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="chart-container">
                <div id="complianceOverviewChart"></div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="chart-container">
                <div id="complianceByCategoryChart"></div>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <!-- 不合规项详情 -->
        <div v-if="currentCheck.failedCount > 0" class="details-section">
          <h3>不合规项详情</h3>
          <el-table
            :data="complianceFailures"
            border
            fit
          >
            <el-table-column prop="checkId" label="检查项ID" width="100" />
            <el-table-column prop="name" label="检查项名称" min-width="200">
              <template #default="scope">
                <el-tooltip :content="scope.row.description" placement="top">
                  <div class="check-name-content">{{ scope.row.name }}</div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="category" label="类别" width="120">
              <template #default="scope">
                <el-tag :type="getCategoryTagType(scope.row.category)">
                  {{ getCategoryLabel(scope.row.category) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="severity" label="风险级别" width="100">
              <template #default="scope">
                <el-tag :type="getRiskLevelTagType(scope.row.severity)">
                  {{ getRiskLevelLabel(scope.row.severity) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="standard" label="标准要求" min-width="150">
              <template #default="scope">
                <div class="standard-requirement">{{ scope.row.standard }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="result" label="检测结果" min-width="200">
              <template #default="scope">
                <div class="check-result">{{ scope.row.result }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="viewFailureDetails(scope.row.id)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 合规项详情 -->
        <div class="details-section">
          <h3>合规项详情</h3>
          <el-table
            :data="compliancePasses"
            border
            fit
          >
            <el-table-column prop="checkId" label="检查项ID" width="100" />
            <el-table-column prop="name" label="检查项名称" min-width="200">
              <template #default="scope">
                <el-tooltip :content="scope.row.description" placement="top">
                  <div class="check-name-content">{{ scope.row.name }}</div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="category" label="类别" width="120">
              <template #default="scope">
                <el-tag :type="getCategoryTagType(scope.row.category)">
                  {{ getCategoryLabel(scope.row.category) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="standard" label="标准要求" min-width="150">
              <template #default="scope">
                <div class="standard-requirement">{{ scope.row.standard }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="result" label="检测结果" min-width="200">
              <template #default="scope">
                <div class="check-result">{{ scope.row.result }}</div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="handleDialogClose">关闭</el-button>
        <el-button @click="exportCheckReport(currentCheck?.id)">导出报告</el-button>
        <el-button @click="shareCheckResult(currentCheck?.id)">分享结果</el-button>
        <el-button type="primary" @click="runComplianceCheck(currentCheck?.id)">
          重新执行
        </el-button>
      </template>
    </el-dialog>

    <!-- 不合规项详情对话框 -->
    <el-dialog
      v-model="failureDetailsDialogVisible"
      title="不合规项详情"
      width="70%"
      :close-on-click-modal="false"
    >
      <div v-if="currentFailure" class="failure-details-container">
        <div class="failure-header">
          <h3>{{ currentFailure.name }}</h3>
          <el-tag :type="getRiskLevelTagType(currentFailure.severity)">
            {{ getRiskLevelLabel(currentFailure.severity) }}
          </el-tag>
        </div>
        
        <div class="failure-content">
          <div class="content-section">
            <h4>描述</h4>
            <p>{{ currentFailure.description }}</p>
          </div>
          
          <div class="content-section">
            <h4>标准要求</h4>
            <p>{{ currentFailure.standard }}</p>
          </div>
          
          <div class="content-section">
            <h4>实际检测结果</h4>
            <div class="detection-result">
              <pre>{{ currentFailure.detectionResult }}</pre>
            </div>
          </div>
          
          <div class="content-section">
            <h4>影响范围</h4>
            <p>{{ currentFailure.impact }}</p>
          </div>
          
          <div class="content-section">
            <h4>修复建议</h4>
            <div class="remediation-steps">
              <h5>步骤：</h5>
              <ol>
                <li v-for="(step, index) in currentFailure.remediationSteps" :key="index">
                  {{ step }}
                </li>
              </ol>
              
              <h5>最佳实践：</h5>
              <p>{{ currentFailure.bestPractices }}</p>
              
              <h5>参考资源：</h5>
              <ul>
                <li v-for="(resource, index) in currentFailure.references" :key="index">
                  <a :href="resource.url" target="_blank">{{ resource.title }}</a>
                </li>
              </ul>
            </div>
          </div>
          
          <div class="content-section">
            <h4>验证方法</h4>
            <p>{{ currentFailure.validationMethod }}</p>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="failureDetailsDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="markAsHandled">标记为已处理</el-button>
        <el-button @click="addRemediationNote">添加修复记录</el-button>
      </template>
    </el-dialog>

    <!-- 修复记录对话框 -->
    <el-dialog
      v-model="remediationNoteDialogVisible"
      title="添加修复记录"
      width="50%"
    >
      <el-form
        :model="remediationNoteForm"
        :rules="remediationNoteRules"
        ref="remediationNoteFormRef"
        label-width="100px"
      >
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="remediationNoteForm.status" placeholder="请选择处理状态">
            <el-option label="已修复" value="fixed" />
            <el-option label="计划修复" value="planned" />
            <el-option label="临时缓解" value="mitigated" />
            <el-option label="无法修复" value="unfixable" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="处理人" prop="handler">
          <el-input v-model="remediationNoteForm.handler" placeholder="请输入处理人" />
        </el-form-item>
        
        <el-form-item label="计划完成日期" prop="plannedDate">
          <el-date-picker
            v-model="remediationNoteForm.plannedDate"
            type="date"
            placeholder="选择计划完成日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="修复说明" prop="description">
          <el-input
            v-model="remediationNoteForm.description"
            placeholder="请输入修复说明"
            type="textarea"
            rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="修复证据">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            multiple
            :on-change="handleFileChange"
            :auto-upload="false"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png/pdf文件，且不超过500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="remediationNoteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRemediationNote">提交</el-button>
      </template>
    </el-dialog>

    <!-- 导出报告对话框 -->
    <el-dialog
      v-model="exportReportDialogVisible"
      title="导出合规报告"
      width="50%"
    >
      <el-form
        :model="exportReportForm"
        :rules="exportReportRules"
        ref="exportReportFormRef"
        label-width="100px"
      >
        <el-form-item label="报告格式" prop="format">
          <el-radio-group v-model="exportReportForm.format">
            <el-radio label="pdf">PDF</el-radio>
            <el-radio label="html">HTML</el-radio>
            <el-radio label="excel">Excel</el-radio>
            <el-radio label="json">JSON</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="报告模板" prop="template">
          <el-select v-model="exportReportForm.template" placeholder="请选择报告模板">
            <el-option label="标准模板" value="standard" />
            <el-option label="详细模板" value="detailed" />
            <el-option label="管理层模板" value="executive" />
            <el-option label="合规证明模板" value="certification" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="报告标题" prop="title">
          <el-input v-model="exportReportForm.title" placeholder="请输入报告标题" />
        </el-form-item>
        
        <el-form-item label="包含内容" prop="includeSections">
          <el-checkbox-group v-model="exportReportForm.includeSections">
            <el-checkbox label="executive_summary">执行摘要</el-checkbox>
            <el-checkbox label="compliance_details">合规详情</el-checkbox>
            <el-checkbox label="failure_details">不合规项详情</el-checkbox>
            <el-checkbox label="remediation_advice">修复建议</el-checkbox>
            <el-checkbox label="evidence">检测证据</el-checkbox>
            <el-checkbox label="charts">图表分析</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="公司信息" prop="companyInfo">
          <el-switch v-model="exportReportForm.companyInfo" />
        </el-form-item>
        
        <el-form-item
          v-if="exportReportForm.companyInfo"
          label="公司名称"
          prop="companyName"
        >
          <el-input v-model="exportReportForm.companyName" placeholder="请输入公司名称" />
        </el-form-item>
        
        <el-form-item label="生成方式" prop="generationMode">
          <el-radio-group v-model="exportReportForm.generationMode">
            <el-radio label="online">在线生成</el-radio>
            <el-radio label="email">发送到邮箱</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item
          v-if="exportReportForm.generationMode === 'email'"
          label="接收邮箱"
          prop="email"
        >
          <el-input v-model="exportReportForm.email" placeholder="请输入接收邮箱" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="exportReportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitExportReport">开始导出</el-button>
      </template>
    </el-dialog>

    <!-- 分享结果对话框 -->
    <el-dialog
      v-model="shareResultDialogVisible"
      title="分享合规检查结果"
      width="50%"
    >
      <div class="share-container">
        <div class="share-options">
          <h4>分享方式</h4>
          <el-radio-group v-model="shareForm.shareType">
            <el-radio label="link">生成分享链接</el-radio>
            <el-radio label="email">发送到邮箱</el-radio>
            <el-radio label="wechat">微信分享</el-radio>
          </el-radio-group>
        </div>
        
        <div v-if="shareForm.shareType === 'link'" class="share-link-container">
          <h4>分享链接</h4>
          <div class="link-content">
            <el-input
              v-model="shareForm.shareLink"
              readonly
              :prefix-icon="shareForm.shareLink ? 'el-icon-check' : 'el-icon-link'"
            >
              <template #append>
                <el-button @click="copyShareLink">复制链接</el-button>
              </template>
            </el-input>
          </div>
          
          <div class="link-expire">
            <el-form-item label="有效期">
              <el-select v-model="shareForm.expireDays" placeholder="请选择有效期">
                <el-option label="1天" value="1" />
                <el-option label="7天" value="7" />
                <el-option label="30天" value="30" />
                <el-option label="永久有效" value="0" />
              </el-select>
            </el-form-item>
          </div>
        </div>
        
        <div v-if="shareForm.shareType === 'email'" class="share-email-container">
          <h4>发送到邮箱</h4>
          <el-form-item>
            <el-input
              v-model="shareForm.email"
              placeholder="请输入接收邮箱"
              maxlength="100"
            />
          </el-form-item>
          
          <el-form-item>
            <el-input
              v-model="shareForm.emailMessage"
              placeholder="请输入邮件说明（可选）"
              type="textarea"
              rows="3"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>
        
        <div v-if="shareForm.shareType === 'wechat'" class="share-wechat-container">
          <h4>微信分享</h4>
          <div class="qrcode-container">
            <div class="qrcode-placeholder">
              <el-empty description="微信扫码分享" />
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="shareResultDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitShareResult">确认分享</el-button>
      </template>
    </el-dialog>

    <!-- 加载遮罩 -->
    <div v-if="showLoading" class="loading-mask">
      <el-loading-spinner>
        <div class="loading-content">
          <el-icon class="is-loading"><loading /></el-icon>
          <p>{{ loadingText }}</p>
        </div>
      </el-loading-spinner>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import * as echarts from 'echarts'
import { Loading } from '@element-plus/icons-vue'
import '../assets/compliance-style.css'

// 图表实例引用
let complianceOverviewChart = null
let complianceByCategoryChart = null

// 页面常量定义
const COMPLIANCE_STANDARDS = {
  'ISO27001': 'ISO 27001',
  'PCI-DSS': 'PCI DSS',
  'GDPR': 'GDPR',
  'HIPAA': 'HIPAA',
  'SOC2': 'SOC 2',
  'NIST': 'NIST'
}

const RISK_LEVELS = {
  'high': { label: '高风险', type: 'danger' },
  'medium': { label: '中风险', type: 'warning' },
  'low': { label: '低风险', type: 'info' }
}

const CHECK_STATUS = {
  'pending': { label: '待执行', type: 'warning' },
  'running': { label: '执行中', type: 'primary' },
  'completed': { label: '已完成', type: 'success' },
  'failed': { label: '执行失败', type: 'danger' },
  'canceled': { label: '已取消', type: 'info' }
}

export default {
  name: 'SecurityCompliance',
  components: {
    Loading
  },
  setup() {
    // 响应式数据
    const loading = ref(false)
    const showLoading = ref(false)
    const loadingText = ref('正在处理...')
    const showAdvancedFilter = ref(false)
    const dateRange = ref([])
    const selectedChecks = ref([])
    
    // 分页数据
    const currentPage = ref(1)
    const pageSize = ref(20)
    const total = ref(0)
    
    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      standard: '',
      status: '',
      severity: '',
      checkType: '',
      targetType: ''
    })
    
    // 合规检查列表
    const complianceChecks = ref([])
    
    // 当前查看的检查
    const currentCheck = ref(null)
    
    // 不合规项和合规项数据
    const complianceFailures = ref([])
    const compliancePasses = ref([])
    
    // 当前查看的不合规项
    const currentFailure = ref(null)
    
    // 图表实例
    let complianceOverviewChart = null
    let complianceByCategoryChart = null
    
    // 合规标准选项
    const complianceStandards = ref([
      { value: 'OWASP_TOP_10', label: 'OWASP Top 10' },
      { value: 'CWE_SANS_TOP_25', label: 'CWE/SANS Top 25' },
      { value: 'PCI_DSS', label: 'PCI DSS' },
      { value: 'GDPR', label: 'GDPR' },
      { value: 'HIPAA', label: 'HIPAA' },
      { value: 'NIST_CSRC', label: 'NIST CSRC' },
      { value: 'ISO27001', label: 'ISO 27001' },
      { value: 'SOC2', label: 'SOC 2' },
      { value: 'CCPA', label: 'CCPA' },
      { value: 'CIS', label: 'CIS Controls' }
    ])
    
    // 对话框状态
    const newCheckDialogVisible = ref(false)
    const checkDetailsDialogVisible = ref(false)
    const failureDetailsDialogVisible = ref(false)
    const remediationNoteDialogVisible = ref(false)
    const exportReportDialogVisible = ref(false)
    const shareResultDialogVisible = ref(false)
    
    // 新建检查表单
    const newCheckForm = reactive({
      name: '',
      description: '',
      standard: [],
      target: '',
      targetType: 'website',
      checkType: 'auto',
      checkScope: [],
      executionMode: 'immediate',
      scheduleTime: '',
      notificationEnabled: false,
      notificationCondition: 'all'
    })
    
    // 修复记录表单
    const remediationNoteForm = reactive({
      status: 'fixed',
      handler: '',
      plannedDate: '',
      description: ''
    })
    
    // 导出报告表单
    const exportReportForm = reactive({
      format: 'pdf',
      template: 'standard',
      title: '',
      includeSections: ['executive_summary', 'compliance_details', 'failure_details'],
      companyInfo: false,
      companyName: '',
      generationMode: 'online',
      email: ''
    })
    
    // 分享表单
    const shareForm = reactive({
      shareType: 'link',
      shareLink: '',
      expireDays: '7',
      email: '',
      emailMessage: ''
    })
    
    // 表单验证规则
    const checkFormRules = {
      name: [
        { required: true, message: '请输入检查名称', trigger: 'blur' },
        { min: 2, max: 100, message: '名称长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      standard: [
        { required: true, message: '请选择合规标准', trigger: 'change' }
      ],
      target: [
        { required: true, message: '请输入检查目标', trigger: 'blur' }
      ]
    }
    
    const remediationNoteRules = {
      status: [
        { required: true, message: '请选择处理状态', trigger: 'change' }
      ],
      handler: [
        { required: true, message: '请输入处理人', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入修复说明', trigger: 'blur' }
      ]
    }
    
    const exportReportRules = {
      format: [
        { required: true, message: '请选择报告格式', trigger: 'change' }
      ],
      template: [
        { required: true, message: '请选择报告模板', trigger: 'change' }
      ],
      title: [
        { required: true, message: '请输入报告标题', trigger: 'blur' }
      ]
    }
    
    // 表单引用
    const checkFormRef = ref(null)
    const remediationNoteFormRef = ref(null)
    const exportReportFormRef = ref(null)
    
    // 统计数据计算属性
    const totalHighRisk = computed(() => {
      return complianceChecks.value.reduce((sum, check) => {
        return check.overallRisk === 'high' ? sum + 1 : sum
      }, 0)
    })
    
    const totalMediumRisk = computed(() => {
      return complianceChecks.value.reduce((sum, check) => {
        return check.overallRisk === 'medium' ? sum + 1 : sum
      }, 0)
    })
    
    const totalLowRisk = computed(() => {
      return complianceChecks.value.reduce((sum, check) => {
        return check.overallRisk === 'low' ? sum + 1 : sum
      }, 0)
    })
    
    const totalCompliant = computed(() => {
      return complianceChecks.value.reduce((sum, check) => {
        return check.overallRisk === 'compliant' ? sum + 1 : sum
      }, 0)
    })
    
    const complianceRate = computed(() => {
      const total = complianceChecks.value.length
      if (total === 0) return 0
      const compliant = totalCompliant.value
      return (compliant / total) * 100
    })
    
    const totalChecks = computed(() => {
      return complianceChecks.value.length
    })
    
    // 辅助函数
    const getStandardLabel = (value) => {
      const item = complianceStandards.value.find(item => item.value === value)
      return item ? item.label : value
    }
    
    const getStandardTagType = (value) => {
      const typeMap = {
        'OWASP_TOP_10': 'primary',
        'PCI_DSS': 'danger',
        'GDPR': 'warning',
        'HIPAA': 'success',
        'ISO27001': 'info'
      }
      return typeMap[value] || 'default'
    }
    
    const getStatusLabel = (value) => {
      const statusMap = {
        'pending': '待执行',
        'running': '执行中',
        'completed': '已完成',
        'failed': '执行失败'
      }
      return statusMap[value] || value
    }
    
    const getStatusTagType = (value) => {
      const typeMap = {
        'pending': 'warning',
        'running': 'info',
        'completed': 'success',
        'failed': 'danger'
      }
      return typeMap[value] || 'default'
    }
    
    const getRiskLevelLabel = (value) => {
      const riskMap = {
        'high': '高风险',
        'medium': '中风险',
        'low': '低风险',
        'compliant': '合规'
      }
      return riskMap[value] || value
    }
    
    const getRiskLevelTagType = (value) => {
      const typeMap = {
        'high': 'danger',
        'medium': 'warning',
        'low': 'info',
        'compliant': 'success'
      }
      return typeMap[value] || 'default'
    }
    
    const getTargetTypeLabel = (value) => {
      const targetMap = {
        'website': '网站',
        'api': 'API',
        'asset_group': '资产组',
        'internal': '内部系统'
      }
      return targetMap[value] || value
    }
    
    const getCategoryLabel = (value) => {
      const categoryMap = {
        'authentication': '身份认证',
        'authorization': '授权访问',
        'data_protection': '数据保护',
        'encryption': '加密机制',
        'input_validation': '输入验证',
        'output_encoding': '输出编码',
        'session_management': '会话管理',
        'error_handling': '错误处理',
        'logging': '日志记录',
        'configuration': '配置管理',
        'dependency_security': '依赖安全',
        'network_security': '网络安全'
      }
      return categoryMap[value] || value
    }
    
    const getCategoryTagType = (value) => {
      const typeMap = {
        'authentication': 'primary',
        'authorization': 'success',
        'data_protection': 'warning',
        'encryption': 'info',
        'input_validation': 'danger',
        'output_encoding': 'info',
        'session_management': 'primary',
        'error_handling': 'warning',
        'logging': 'info',
        'configuration': 'success',
        'dependency_security': 'danger',
        'network_security': 'warning'
      }
      return typeMap[value] || 'default'
    }
    
    // API调用函数
    const fetchComplianceChecks = async () => {
      loading.value = true
      try {
        // 模拟API调用
        // const response = await apiService.getComplianceChecks({
        //   page: currentPage.value,
        //   pageSize: pageSize.value,
        //   keyword: searchForm.keyword,
        //   standard: searchForm.standard,
        //   status: searchForm.status,
        //   severity: searchForm.severity,
        //   checkType: searchForm.checkType,
        //   targetType: searchForm.targetType,
        //   startDate: dateRange.value[0] || '',
        //   endDate: dateRange.value[1] || ''
        // })
        
        // 模拟数据
        complianceChecks.value = [
          {
            id: 1,
            name: 'PCI DSS合规检查 - 支付系统',
            description: '针对支付系统的PCI DSS合规性全面检查',
            standard: ['PCI_DSS'],
            target: 'https://payment.example.com',
            targetType: 'website',
            status: 'completed',
            overallRisk: 'medium',
            checkCount: 32,
            failedCount: 4,
            passedCount: 28,
            complianceRate: 87.5,
            startTime: '2023-11-20 09:30:00',
            endTime: '2023-11-20 10:15:30',
            createdBy: 'admin',
            createdAt: '2023-11-20 09:25:00'
          },
          {
            id: 2,
            name: 'OWASP Top 10 API安全检查',
            description: '按照OWASP Top 10标准对API进行安全检查',
            standard: ['OWASP_TOP_10'],
            target: 'https://api.example.com',
            targetType: 'api',
            status: 'completed',
            overallRisk: 'high',
            checkCount: 20,
            failedCount: 6,
            passedCount: 14,
            complianceRate: 70.0,
            startTime: '2023-11-19 14:20:00',
            endTime: '2023-11-19 14:45:20',
            createdBy: 'security_team',
            createdAt: '2023-11-19 14:15:00'
          },
          {
            id: 3,
            name: 'GDPR数据保护合规检查',
            description: '针对用户数据处理的GDPR合规性检查',
            standard: ['GDPR'],
            target: 'user-data-system',
            targetType: 'internal',
            status: 'completed',
            overallRisk: 'low',
            checkCount: 18,
            failedCount: 2,
            passedCount: 16,
            complianceRate: 88.9,
            startTime: '2023-11-18 11:00:00',
            endTime: '2023-11-18 11:30:45',
            createdBy: 'compliance_officer',
            createdAt: '2023-11-18 10:55:00'
          },
          {
            id: 4,
            name: 'ISO 27001信息安全管理检查',
            description: '按照ISO 27001标准进行信息安全管理体系检查',
            standard: ['ISO27001'],
            target: 'all-systems',
            targetType: 'asset_group',
            status: 'completed',
            overallRisk: 'compliant',
            checkCount: 45,
            failedCount: 0,
            passedCount: 45,
            complianceRate: 100.0,
            startTime: '2023-11-17 16:00:00',
            endTime: '2023-11-17 17:45:10',
            createdBy: 'iso_auditor',
            createdAt: '2023-11-17 15:50:00'
          },
          {
            id: 5,
            name: 'HIPAA医疗数据合规检查',
            description: '针对医疗健康数据的HIPAA合规性检查',
            standard: ['HIPAA'],
            target: 'https://health-records.example.com',
            targetType: 'website',
            status: 'running',
            overallRisk: 'pending',
            checkCount: 25,
            failedCount: 0,
            passedCount: 0,
            complianceRate: 0,
            startTime: '2023-11-20 15:30:00',
            endTime: null,
            createdBy: 'health_admin',
            createdAt: '2023-11-20 15:25:00'
          }
        ]
        
        total.value = 120 // 模拟总数
      } catch (error) {
        ElMessage.error('获取合规检查列表失败')
        console.error('Failed to fetch compliance checks:', error)
      } finally {
        loading.value = false
      }
    }
    
    const fetchComplianceDetails = async (checkId) => {
      showLoading.value = true
      loadingText.value = '正在获取合规检查详情...'
      try {
        // 模拟API调用
        // const response = await apiService.getComplianceCheckDetails(checkId)
        
        // 模拟数据
        currentCheck.value = {
          id: checkId,
          name: 'PCI DSS合规检查 - 支付系统',
          description: '针对支付系统的PCI DSS合规性全面检查，包含32项检查点，涵盖数据安全、加密机制、访问控制等关键领域。',
          standard: ['PCI_DSS'],
          target: 'https://payment.example.com',
          targetType: 'website',
          status: 'completed',
          overallRisk: 'medium',
          checkCount: 32,
          failedCount: 4,
          passedCount: 28,
          complianceRate: 87.5,
          startTime: '2023-11-20 09:30:00',
          endTime: '2023-11-20 10:15:30',
          createdBy: 'admin',
          createdAt: '2023-11-20 09:25:00'
        }
        
        // 模拟不合规项数据
        complianceFailures.value = [
          {
            id: 101,
            checkId: 'PCI-DSS-2.2',
            name: '系统配置加固不足',
            description: '检查系统是否移除了不必要的服务、协议和功能',
            category: 'configuration',
            severity: 'high',
            standard: 'PCI DSS 2.2: 开发和维护安全系统和应用程序',
            result: '发现多个不必要的服务和端口处于开启状态',
            detectionResult: '系统开放了FTP(21)、Telnet(23)和SMTP(25)等非必要服务端口',
            impact: '可能被攻击者利用进行未授权访问和数据泄露',
            remediationSteps: [
              '关闭所有非必要的服务和端口',
              '实施最小权限原则',
              '定期审查系统配置',
              '使用防火墙限制访问'
            ],
            bestPractices: '仅保留业务必需的服务和端口，所有其他服务应禁用或移除',
            references: [
              { title: 'PCI DSS 2.2 要求', url: 'https://www.pcisecuritystandards.org/document_library' },
              { title: '系统加固最佳实践', url: 'https://example.com/system-hardening' }
            ],
            validationMethod: '使用端口扫描工具验证所有非必要端口已关闭'
          },
          {
            id: 102,
            checkId: 'PCI-DSS-3.4',
            name: '传输中数据加密不足',
            description: '检查传输中的敏感数据是否使用强加密',
            category: 'encryption',
            severity: 'high',
            standard: 'PCI DSS 3.4: 传输中的敏感数据使用强加密',
            result: '发现部分API调用未使用TLS 1.2或更高版本',
            detectionResult: '登录API (/api/login)仅支持TLS 1.0，不符合PCI DSS要求',
            impact: '传输中的数据可能被中间人攻击截获和窃取',
            remediationSteps: [
              '配置Web服务器仅支持TLS 1.2及更高版本',
              '禁用所有低于TLS 1.2的协议',
              '更新SSL证书',
              '实施HSTS策略'
            ],
            bestPractices: '始终使用TLS 1.2或更高版本，配置适当的密码套件',
            references: [
              { title: 'PCI DSS 3.4 要求', url: 'https://www.pcisecuritystandards.org/document_library' },
              { title: 'TLS配置最佳实践', url: 'https://example.com/tls-best-practices' }
            ],
            validationMethod: '使用SSL Labs等工具验证TLS配置符合要求'
          },
          {
            id: 103,
            checkId: 'PCI-DSS-8.2.1',
            name: '账户管理存在缺陷',
            description: '检查用户账户管理流程是否符合安全要求',
            category: 'authentication',
            severity: 'medium',
            standard: 'PCI DSS 8.2.1: 为每个访问系统组件的用户分配唯一ID',
            result: '发现多个共享账户',
            detectionResult: '系统中存在至少3个共享管理员账户',
            impact: '无法追踪具体用户操作，增加安全审计难度',
            remediationSteps: [
              '为每个用户创建唯一账户',
              '删除所有共享账户',
              '实施强密码策略',
              '配置账户锁定机制'
            ],
            bestPractices: '确保每个用户都有唯一的账户，便于审计和责任追踪',
            references: [
              { title: 'PCI DSS 8.2.1 要求', url: 'https://www.pcisecuritystandards.org/document_library' },
              { title: '账户管理最佳实践', url: 'https://example.com/account-management' }
            ],
            validationMethod: '审查用户账户列表，确保没有共享账户'
          },
          {
            id: 104,
            checkId: 'PCI-DSS-10.2',
            name: '日志记录不完整',
            description: '检查系统是否记录了所有必要的安全事件',
            category: 'logging',
            severity: 'medium',
            standard: 'PCI DSS 10.2: 跟踪和监控对网络资源和持卡人数据的所有访问',
            result: '发现部分系统操作未记录到安全日志',
            detectionResult: 'API访问日志缺少详细的用户操作记录',
            impact: '无法进行完整的安全审计和事件溯源',
            remediationSteps: [
              '配置所有系统组件记录详细日志',
              '包括日期、时间、用户、操作类型等信息',
              '集中存储日志文件',
              '配置日志保留策略'
            ],
            bestPractices: '记录所有安全相关事件，确保日志的完整性和不可篡改性',
            references: [
              { title: 'PCI DSS 10.2 要求', url: 'https://www.pcisecuritystandards.org/document_library' },
              { title: '日志管理最佳实践', url: 'https://example.com/log-management' }
            ],
            validationMethod: '审查日志内容，确保包含所有必要的安全事件信息'
          }
        ]
        
        // 模拟合规项数据
        compliancePasses.value = [
          {
            id: 201,
            checkId: 'PCI-DSS-3.2',
            name: '存储数据加密',
            description: '检查存储的敏感数据是否使用强加密',
            category: 'data_protection',
            standard: 'PCI DSS 3.2: 存储的敏感数据使用强加密',
            result: '所有存储的敏感数据均使用AES-256加密'
          },
          {
            id: 202,
            checkId: 'PCI-DSS-7.1',
            name: '访问控制实施',
            description: '检查系统是否实施了严格的访问控制',
            category: 'authorization',
            standard: 'PCI DSS 7.1: 实施最小权限原则的访问控制',
            result: '系统正确实施了基于角色的访问控制'
          },
          {
            id: 203,
            checkId: 'PCI-DSS-9.1',
            name: '物理访问控制',
            description: '检查物理访问控制措施是否到位',
            category: 'authorization',
            standard: 'PCI DSS 9.1: 限制对持卡人数据环境的物理访问',
            result: '数据中心实施了严格的物理访问控制'
          }
        ]
        
        initCharts()
      } catch (error) {
        ElMessage.error('获取合规检查详情失败')
        console.error('Failed to fetch compliance details:', error)
      } finally {
        showLoading.value = false
      }
    }
    
    const fetchFailureDetails = async (failureId) => {
      showLoading.value = true
      loadingText.value = '正在获取不合规项详情...'
      try {
        // 模拟API调用
        // const response = await apiService.getComplianceFailureDetails(failureId)
        
        // 从现有数据中查找
        currentFailure.value = complianceFailures.value.find(item => item.id === failureId)
      } catch (error) {
        ElMessage.error('获取不合规项详情失败')
        console.error('Failed to fetch failure details:', error)
      } finally {
        showLoading.value = false
      }
    }
    
    const createComplianceCheck = async (formData) => {
      showLoading.value = true
      loadingText.value = '正在创建合规检查...'
      try {
        // 模拟API调用
        // const response = await apiService.createComplianceCheck(formData)
        
        ElMessage.success('合规检查创建成功')
        newCheckDialogVisible.value = false
        resetCheckForm()
        fetchComplianceChecks()
      } catch (error) {
        ElMessage.error('创建合规检查失败')
        console.error('Failed to create compliance check:', error)
      } finally {
        showLoading.value = false
      }
    }
    
    const runComplianceCheck = async (checkId) => {
      try {
        await ElMessageBox.confirm(
          '确定要执行此合规检查吗？',
          '确认执行',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        showLoading.value = true
        loadingText.value = '正在执行合规检查...'
        
        // 模拟API调用
        // const response = await apiService.runComplianceCheck(checkId)
        
        setTimeout(() => {
          ElMessage.success('合规检查已开始执行')
          fetchComplianceChecks()
          showLoading.value = false
        }, 1500)
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('执行合规检查失败')
          console.error('Failed to run compliance check:', error)
        }
        showLoading.value = false
      }
    }
    
    const deleteComplianceCheck = async (checkId) => {
      try {
        await ElMessageBox.confirm(
          '确定要删除此合规检查吗？此操作不可撤销。',
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          }
        )
        
        showLoading.value = true
        loadingText.value = '正在删除合规检查...'
        
        // 模拟API调用
        // const response = await apiService.deleteComplianceCheck(checkId)
        
        ElMessage.success('合规检查已删除')
        fetchComplianceChecks()
        showLoading.value = false
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除合规检查失败')
          console.error('Failed to delete compliance check:', error)
        }
        showLoading.value = false
      }
    }
    
    const exportCheckReport = async (checkId) => {
      if (!checkId) return
      
      exportReportForm.title = `合规检查报告 - ${currentCheck.value?.name || '未命名'}`
      exportReportDialogVisible.value = true
    }
    
    const shareCheckResult = async (checkId) => {
      if (!checkId) return
      
      // 生成模拟分享链接
      shareForm.shareLink = `https://vulnerability-scanner.example.com/share/compliance/${checkId}?token=abc123xyz`
      shareResultDialogVisible.value = true
    }
    
    // 图表初始化
    const initCharts = () => {
      // 合规概览饼图
      if (!complianceOverviewChart) {
        complianceOverviewChart = echarts.init(document.getElementById('complianceOverviewChart'))
      }
      
      const overviewOption = {
        title: {
          text: '合规状态分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '合规状态',
            type: 'pie',
            radius: '50%',
            data: [
              { value: currentCheck.value?.passedCount || 0, name: '合规项' },
              { value: currentCheck.value?.failedCount || 0, name: '不合规项' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      
      complianceOverviewChart.setOption(overviewOption)
      
      // 按类别合规性柱状图
      if (!complianceByCategoryChart) {
        complianceByCategoryChart = echarts.init(document.getElementById('complianceByCategoryChart'))
      }
      
      // 模拟按类别统计数据
      const categoryData = [
        { name: '身份认证', compliant: 5, nonCompliant: 1 },
        { name: '授权访问', compliant: 4, nonCompliant: 0 },
        { name: '数据保护', compliant: 3, nonCompliant: 1 },
        { name: '加密机制', compliant: 2, nonCompliant: 1 },
        { name: '输入验证', compliant: 4, nonCompliant: 0 },
        { name: '会话管理', compliant: 3, nonCompliant: 1 }
      ]
      
      const categoryOption = {
        title: {
          text: '按类别合规性统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['合规', '不合规'],
          bottom: 0
        },
        xAxis: {
          type: 'category',
          data: categoryData.map(item => item.name),
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '合规',
            type: 'bar',
            data: categoryData.map(item => item.compliant),
            itemStyle: {
              color: '#67C23A'
            }
          },
          {
            name: '不合规',
            type: 'bar',
            data: categoryData.map(item => item.nonCompliant),
            itemStyle: {
              color: '#F56C6C'
            }
          }
        ]
      }
      
      complianceByCategoryChart.setOption(categoryOption)
    }
    
    // 事件处理函数
    const handleSearch = () => {
      currentPage.value = 1
      fetchComplianceChecks()
    }
    
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      dateRange.value = []
      currentPage.value = 1
      fetchComplianceChecks()
    }
    
    const toggleAdvancedFilter = () => {
      showAdvancedFilter.value = !showAdvancedFilter.value
    }
    
    const handleSelectionChange = (selection) => {
      selectedChecks.value = selection
    }
    
    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      currentPage.value = 1
      fetchComplianceChecks()
    }
    
    const handleCurrentChange = (newCurrent) => {
      currentPage.value = newCurrent
      fetchComplianceChecks()
    }
    
    const handleHeaderCommand = (command) => {
      switch (command) {
        case 'batchDelete':
          confirmBatchDelete()
          break
        case 'exportResults':
          ElMessage.info('导出功能开发中')
          break
        case 'refresh':
          fetchComplianceChecks()
          break
      }
    }
    
    const handleActionCommand = (command, checkId) => {
      switch (command) {
        case 'edit':
          ElMessage.info('编辑功能开发中')
          break
        case 'export':
          exportCheckReport(checkId)
          break
        case 'share':
          shareCheckResult(checkId)
          break
        case 'clone':
          ElMessage.info('克隆功能开发中')
          break
        case 'delete':
          deleteComplianceCheck(checkId)
          break
      }
    }
    
    const openNewCheckDialog = () => {
      resetCheckForm()
      newCheckDialogVisible.value = true
    }
    
    const handleDialogClose = () => {
      // 关闭所有对话框
      newCheckDialogVisible.value = false
      checkDetailsDialogVisible.value = false
      failureDetailsDialogVisible.value = false
      remediationNoteDialogVisible.value = false
      exportReportDialogVisible.value = false
      shareResultDialogVisible.value = false
      
      // 重置表单
      resetCheckForm()
      resetRemediationNoteForm()
      resetExportReportForm()
      resetShareForm()
    }
    
    const submitCheckForm = () => {
      checkFormRef.value.validate(async (valid) => {
        if (valid) {
          await createComplianceCheck({ ...newCheckForm })
        }
      })
    }
    
    const resetCheckForm = () => {
      if (checkFormRef.value) {
        checkFormRef.value.resetFields()
      }
      Object.assign(newCheckForm, {
        name: '',
        description: '',
        standard: [],
        target: '',
        targetType: 'website',
        checkType: 'auto',
        checkScope: [],
        executionMode: 'immediate',
        scheduleTime: '',
        notificationEnabled: false,
        notificationCondition: 'all'
      })
    }
    
    const viewComplianceDetails = (checkId) => {
      fetchComplianceDetails(checkId)
      checkDetailsDialogVisible.value = true
    }
    
    const viewFailureDetails = (failureId) => {
      fetchFailureDetails(failureId)
      failureDetailsDialogVisible.value = true
    }
    
    const markAsHandled = () => {
      ElMessage.success('已标记为已处理')
      failureDetailsDialogVisible.value = false
    }
    
    const addRemediationNote = () => {
      resetRemediationNoteForm()
      remediationNoteDialogVisible.value = true
    }
    
    const submitRemediationNote = () => {
      remediationNoteFormRef.value.validate(() => {
        ElMessage.success('修复记录已提交')
        remediationNoteDialogVisible.value = false
      })
    }
    
    const resetRemediationNoteForm = () => {
      if (remediationNoteFormRef.value) {
        remediationNoteFormRef.value.resetFields()
      }
      Object.assign(remediationNoteForm, {
        status: 'fixed',
        handler: '',
        plannedDate: '',
        description: ''
      })
    }
    
    const submitExportReport = () => {
      exportReportFormRef.value.validate(() => {
        ElMessage.success('报告导出任务已提交')
        exportReportDialogVisible.value = false
      })
    }
    
    const resetExportReportForm = () => {
      if (exportReportFormRef.value) {
        exportReportFormRef.value.resetFields()
      }
      Object.assign(exportReportForm, {
        format: 'pdf',
        template: 'standard',
        title: '',
        includeSections: ['executive_summary', 'compliance_details', 'failure_details'],
        companyInfo: false,
        companyName: '',
        generationMode: 'online',
        email: ''
      })
    }
    
    const submitShareResult = () => {
      ElMessage.success('分享成功')
      shareResultDialogVisible.value = false
    }
    
    const resetShareForm = () => {
      Object.assign(shareForm, {
        shareType: 'link',
        shareLink: '',
        expireDays: '7',
        email: '',
        emailMessage: ''
      })
    }
    
    const copyShareLink = () => {
      navigator.clipboard.writeText(shareForm.shareLink)
        .then(() => {
          ElMessage.success('链接已复制到剪贴板')
        })
        .catch(() => {
          ElMessage.error('复制失败，请手动复制')
        })
    }
    
    const confirmBatchDelete = () => {
      if (selectedChecks.value.length === 0) {
        ElMessage.warning('请先选择要删除的合规检查')
        return
      }
      
      ElMessageBox.confirm(
        `确定要删除选中的 ${selectedChecks.value.length} 项合规检查吗？此操作不可撤销。`,
        '确认批量删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }
      ).then(() => {
        showLoading.value = true
        loadingText.value = '正在批量删除...'
        
        // 模拟批量删除
        setTimeout(() => {
          ElMessage.success('批量删除成功')
          selectedChecks.value = []
          fetchComplianceChecks()
          showLoading.value = false
        }, 1500)
      }).catch(() => {
        // 用户取消操作
      })
    }
    
    const batchRunChecks = () => {
      if (selectedChecks.value.length === 0) {
        ElMessage.warning('请先选择要执行的合规检查')
        return
      }
      
      ElMessageBox.confirm(
        `确定要执行选中的 ${selectedChecks.value.length} 项合规检查吗？`,
        '确认批量执行',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        showLoading.value = true
        loadingText.value = '正在批量执行...'
        
        // 模拟批量执行
        setTimeout(() => {
          ElMessage.success('批量执行已开始')
          fetchComplianceChecks()
          showLoading.value = false
        }, 1500)
      }).catch(() => {
        // 用户取消操作
      })
    }
    
    const batchExportReports = () => {
      if (selectedChecks.value.length === 0) {
        ElMessage.warning('请先选择要导出的合规检查')
        return
      }
      
      ElMessage.info('批量导出功能开发中')
    }
    
    const clearSelection = () => {
      selectedChecks.value = []
    }
    
    const handleFileChange = (file, fileList) => {
      // 文件上传处理
      console.log('File changed:', file, fileList)
    }
    
    // 生命周期钩子
    onMounted(() => {
      fetchComplianceChecks()
      
      // 监听窗口大小变化，重新渲染图表
      window.addEventListener('resize', () => {
        if (complianceOverviewChart) {
          complianceOverviewChart.resize()
        }
        if (complianceByCategoryChart) {
          complianceByCategoryChart.resize()
        }
      })
    })
    
    onUnmounted(() => {
      // 销毁图表实例
      if (complianceOverviewChart) {
        complianceOverviewChart.dispose()
      }
      if (complianceByCategoryChart) {
        complianceByCategoryChart.dispose()
      }
      
      // 移除事件监听器
      window.removeEventListener('resize', () => {
        if (complianceOverviewChart) {
          complianceOverviewChart.resize()
        }
        if (complianceByCategoryChart) {
          complianceByCategoryChart.resize()
        }
      })
    })
    
    return {
      // 响应式数据
      loading,
      showLoading,
      loadingText,
      showAdvancedFilter,
      dateRange,
      selectedChecks,
      currentPage,
      pageSize,
      total,
      searchForm,
      complianceChecks,
      currentCheck,
      complianceFailures,
      compliancePasses,
      currentFailure,
      complianceStandards,
      
      // 对话框状态
      newCheckDialogVisible,
      checkDetailsDialogVisible,
      failureDetailsDialogVisible,
      remediationNoteDialogVisible,
      exportReportDialogVisible,
      shareResultDialogVisible,
      
      // 表单数据
      newCheckForm,
      remediationNoteForm,
      exportReportForm,
      shareForm,
      
      // 表单引用
      checkFormRef,
      remediationNoteFormRef,
      exportReportFormRef,
      
      // 表单验证规则
      checkFormRules,
      remediationNoteRules,
      exportReportRules,
      
      // 计算属性
      totalHighRisk,
      totalMediumRisk,
      totalLowRisk,
      totalCompliant,
      complianceRate,
      totalChecks,
      
      // 辅助函数
      getStandardLabel,
      getStandardTagType,
      getStatusLabel,
      getStatusTagType,
      getRiskLevelLabel,
      getRiskLevelTagType,
      getTargetTypeLabel,
      getCategoryLabel,
      getCategoryTagType,
      
      // 事件处理函数
      handleSearch,
      resetSearch,
      toggleAdvancedFilter,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleHeaderCommand,
      handleActionCommand,
      openNewCheckDialog,
      handleDialogClose,
      submitCheckForm,
      resetCheckForm,
      viewComplianceDetails,
      viewFailureDetails,
      markAsHandled,
      addRemediationNote,
      submitRemediationNote,
      resetRemediationNoteForm,
      submitExportReport,
      resetExportReportForm,
      submitShareResult,
      resetShareForm,
      copyShareLink,
      confirmBatchDelete,
      batchRunChecks,
      batchExportReports,
      clearSelection,
      runComplianceCheck,
      deleteComplianceCheck,
      exportCheckReport,
      shareCheckResult,
      handleFileChange
    }
  }
}
</script>

<!-- 样式导入 -->
<style>
@import '../assets/compliance-style.css';
</style>